﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinListView;
using PdfLucene.src;

using System.IO;

namespace PdfLucene
{
  
    public partial class frmInterfazPrincipal2 : Form
    {


        private LuceneIndexer index;
        //private Lucene.Net.Analysis.Snowball.SnowballAnalyzer sbAnalyzer;
        private bool hayIndice;
        public frmInterfazPrincipal2()
        {
            InitializeComponent();
        }

        private void frmInterfazPrincipal2_Load(object sender, EventArgs e)
        {
            Infragistics.Win.AppStyling.StyleManager.Load(@"Styles\RubberBlack.isl");
            LLenarForma();
            index = new LuceneIndexer();
            SeleccionarPanelIndice();

        }
        private void SeleccionarPanelIndice(){
            //panelBuscar.Dock = DockStyle.None;
            //panelIndice.Dock = DockStyle.Right;
            //panelBuscar.Visible = false;
            //panelIndice.Visible = true;
            ultraTabControl1.SelectedTab = ultraTabControl1.Tabs[1];
        }

        private void SeleccionarPanelBusqueda()
        {
            //panelIndice.Dock = DockStyle.None;
            //panelBuscar.Dock = DockStyle.Right;
            //panelIndice.Visible = false;
            //panelBuscar.Visible = true;
            ultraTabControl1.SelectedTab = ultraTabControl1.Tabs[0];
        }
        private void LLenarForma()
        {
            txtPdfDir.Text = PdfLucene.Properties.Settings.Default.PDFFolder;
             if (Directory.Exists(@"./" + Constantes.INDEX_DIRECTORY))
            {
                hayIndice = true;
                lblMustraIndice.Text= "Recrear Indice";
                ultraButton1.Text = "Reconstruir Indice";
                ultraGroupBox3.Visible = true;
                //linkLabel1.Visible = false;
                linkLabel1.Visible = false;
                ultraPanel1.Visible = true;
            }
            else
            {
                hayIndice = false;
                lblMustraIndice.Text = "Crear Indice";
                ultraButton1.Text = "Construir Indice";
                ultraGroupBox3.Visible = false;
                linkLabel1.Visible = true;
                ultraPanel1.Visible = false;


            }



        }


        private void txtPdfDir_EditorButtonClick(object sender, Infragistics.Win.UltraWinEditors.EditorButtonEventArgs e)
        {
            try
            {
                if (e.Button.AccessibleName.Equals("btnOpenDialogDir"))
                {
                    if (Directory.Exists(txtPdfDir.Text))
                    {
                        folderBrowserDialog1.SelectedPath = PdfLucene.Properties.Settings.Default.PDFFolder;
                    }
                    DialogResult result = folderBrowserDialog1.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        txtPdfDir.Text = folderBrowserDialog1.SelectedPath;
                        PdfLucene.Properties.Settings.Default.PDFFolder = txtPdfDir.Text;
                        PdfLucene.Properties.Settings.Default.Save();
                    }
                }
                else
                {
                    PdfLucene.Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
            
        }

        private void btnMostrarDir_Click(object sender, EventArgs e)
        {

        }

        private void txtPDF_EditorButtonClick(object sender, Infragistics.Win.UltraWinEditors.EditorButtonEventArgs e)
        {
            if (e.Button.AccessibleName.Equals("btnOpenDialogDir"))
            {
                openFileDialog1.Filter = "Archivos pdf(*.pdf)|*.pdf";
                openFileDialog1.InitialDirectory = PdfLucene.Properties.Settings.Default.PDFFolder;
                openFileDialog1.Title = "Selecciona el PDF";
                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    txtPDF.Text = openFileDialog1.FileName;
                }

	        }
            
        }

        private void btnMuestraIndice_Click(object sender, EventArgs e)
        {
            SeleccionarPanelIndice();

        }

        private void btnMostrarBuscar_Click(object sender, EventArgs e)
        {
            SeleccionarPanelBusqueda();

            //panelIndice.SendToBack();

        }


        private void ultraButton1_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(txtPdfDir.Text))
            {
                PdfLucene.Properties.Settings.Default.PDFFolder = txtPdfDir.Text;
                PdfLucene.Properties.Settings.Default.Save();
                CreandoIndice frmCrearIndice = new CreandoIndice();
                frmCrearIndice.EmpezarConstruirIndice(txtPdfDir.Text, index);
                index.CloseIndex();
                LLenarForma();
                Refresh();
            }
            else
            {
                MessageBox.Show("Directorio ingresado no es valido", "ERROR");
            }

        }

        private void txtPDF_ValueChanged(object sender, EventArgs e)
        {

        }

        private void ultraButton2_Click(object sender, EventArgs e)
        {
            if (File.Exists(txtPDF.Text))
            {
                FileInfo fileInfo = new FileInfo(txtPDF.Text);
                if (fileInfo.Extension == ".pdf")
                {
                    if (Directory.Exists(Constantes.INDEX_DIRECTORY))
                    {
                        try
                        {
                            index.ContinueIndexFile();
                            PDFFile pdf = PDFManager.GetFileContents(fileInfo);
                            index.IndexDocument(pdf);
                            MessageBox.Show("EXITO: El archivo '"+fileInfo.Name+"' ha sido agregado al indice", "EXITO");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("ERROR: No se pudo Agregar el archivo pdf al indice", "ERROR");
                        }
                        finally
                        {
                            index.CloseIndex();
                        }

                    }
                }
                else
                {
                    MessageBox.Show("Archivo ingresado no es un pdf", "ERROR");
                }

            }
            else
            {
                MessageBox.Show("Archivo ingresado no es valido", "ERROR");
            }
        }
        private void FillGrid(List<PdfSearchResult> hits)
        {
            ultraListView1.Items.Clear();
            foreach (PdfSearchResult hit in hits)
            {

                Infragistics.Win.UltraWinListView.UltraListViewItem ultraListViewItem = new Infragistics.Win.UltraWinListView.UltraListViewItem(hit.FileName, new Infragistics.Win.UltraWinListView.UltraListViewSubItem[] {
            new Infragistics.Win.UltraWinListView.UltraListViewSubItem(hit.Score +"", null),
            new Infragistics.Win.UltraWinListView.UltraListViewSubItem(hit.Path, null),
            new Infragistics.Win.UltraWinListView.UltraListViewSubItem(hit.ModifiedTime, null),
            new Infragistics.Win.UltraWinListView.UltraListViewSubItem(hit.IndexId,null)    
                }, null);
                ultraListView1.Items.Add(ultraListViewItem);
            }
 
        }
        private void ultraButton3_Click(object sender, EventArgs e)
        {
            PdfLucene.QueryExpansions expansionType = QueryExpansions.None;
            if (txtConsulta.Text == string.Empty)
            {
                MessageBox.Show("ERROR: No se especifico cadena a buscar", "ERROR");
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            //Autocomplete list
            txtConsulta.Items.Add(txtConsulta.Text);
            
            List<PdfSearchResult> hits = null;
            //Lematizar
            if (uceSinonimos.Checked)
                expansionType = QueryExpansions.WordNet;
            if (uceLematizador.Checked)
                expansionType = QueryExpansions.Lemmatizer;               

            if(ultraOptionSet1.CheckedIndex == 0)
                hits = LuceneIndexer.SearchIndexByContent(txtConsulta.Text,expansionType);
            if (ultraOptionSet1.CheckedIndex == 1)
                hits = LuceneIndexer.SearchIndexByAbstract(txtConsulta.Text,expansionType);
            if (ultraOptionSet1.CheckedIndex == 2)
                hits = LuceneIndexer.SearchIndexByNote(txtConsulta.Text,expansionType);

            FillGrid(hits);
            this.Cursor = Cursors.Default;
            
        }

        private void ultraListView1_ItemActivated(object sender, Infragistics.Win.UltraWinListView.ItemActivatedEventArgs e)
        {

            
        }

        private void ultraListView1_ItemDoubleClick(object sender, Infragistics.Win.UltraWinListView.ItemDoubleClickEventArgs e)
        {
            string tx= (ultraListView1.SelectedItems[0]).SubItems[1].Text;
            System.Diagnostics.Process.Start(tx);
        }

        private void ultraListView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                UltraListView listView = sender as UltraListView;
                if (listView != null)
                {
                    UltraListViewItem item = listView.ItemFromPoint(e.Location);
                    if (item != null)
                    {
                        PdfSearchResult file = LuceneIndexer.ReadDocument(int.Parse(item.SubItems["indexId"].Text));
                        ucPopWindowPreview.PdfFile =  file;
                        ucPopWindowPreview.LoadFile();
                        popUpContainer.Show(); 
                    }
                }
            }
        }

        private void txtConsulta_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void ultraButton3_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void txtConsulta_KeyDown(object sender, KeyEventArgs e)
        {
           
        }

        private void txtConsulta_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.ultraButton3_Click(sender, e);
            }
        }

        private void ultraOptionSet1_ValueChanged(object sender, EventArgs e)
        {
            this.ultraButton3.Text = "Buscar " + ultraOptionSet1.CheckedItem.DisplayText;
        }

        private void uegbOptions_ExpandedStateChanged(object sender, EventArgs e)
        {
            ultraLabel2.Top = uegbOptions.Bottom + 10;
            ultraListView1.Top = ultraLabel2.Bottom + 20;
        }

        private void uceSinonimos_CheckedChanged(object sender, EventArgs e)
        {
            uceLematizador.Checked = (uceSinonimos.Checked)?false:uceLematizador.Checked;
        }

        private void uceLematizador_CheckedChanged(object sender, EventArgs e)
        {
            uceSinonimos.Checked = (uceLematizador.Checked)?false:uceSinonimos.Checked;
        }

    }
}
